// This code is in the public domain -- castano@gmail.com

#include "MeshExportOBJ.h"

#include <nvcore/StrLib.h>
#include <nvcore/StdStream.h>
#include <nvcore/TextWriter.h>

#include <nvmesh/halfedge/HalfEdgeMesh.h>
#include <nvmesh/halfedge/HalfEdgeVertex.h>
#include <nvmesh/halfedge/HalfEdgeFace.h>
#include <nvmesh/halfedge/HalfEdge.h>

using namespace nv;
using namespace nv::HalfEdge;

bool nv::exportMesh(const HalfEdge::Mesh * mesh, const char * name)
{
    nvDebugCheck(mesh != NULL);
    nvDebugCheck(name != NULL);

    if (strCaseCmp(Path::extension(name), ".obj") == 0)
    {
        StdOutputStream stream(name);
        return exportMesh_OBJ(mesh, &stream);
    }

    return false;
}

bool nv::exportMesh_OBJ(const HalfEdge::Mesh * mesh, Stream * stream)
{
    nvDebugCheck(mesh != NULL);
    nvDebugCheck(stream != NULL);

    TextWriter writer(stream);

    writer.write("# OBJ mesh generated by nvmesh (%s - %s)\n", __DATE__, __TIME__);

    // Write vertices.
    for (Mesh::ConstVertexIterator v = mesh->vertices(); !v.isDone(); v.advance())
    {
        const Vertex * vertex = v.current();
        writer.write("v %f %f %f\n", vertex->pos().x(), vertex->pos().y(), vertex->pos().z());
    }
    for (Mesh::ConstVertexIterator v = mesh->vertices(); !v.isDone(); v.advance())
    {
        const Vertex * vertex = v.current();
        writer.write("vn %f %f %f\n", vertex->nor().x(), vertex->nor().y(), vertex->nor().z());
    }

    // Write faces.
    for (Mesh::ConstFaceIterator f = mesh->faces(); !f.isDone(); f.advance())
    {
        const Face * face = f.current();
        
        writer.writeString("f");

        for (Face::ConstEdgeIterator e = face->edges(); !e.isDone(); e.advance())
        {
            const Vertex * vertex = e.current()->vertex();

            writer.write(" %d//%d", vertex->id() + 1, vertex->id() + 1);
        }

        writer.writeString("\n");
    }

    return true;
}
	
